package com.aliyun.messagemgt.application.service.Impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.messagemgt.common.dto.send.PushChannelInfo;
import com.aliyun.messagemgt.application.service.TokenUtil;
import com.aliyun.messagemgt.common.base.HttpClientResult;
import com.aliyun.messagemgt.util.HttpClientUtils;
import com.aliyun.messagemgt.common.constants.WeixinConstant;
import com.aliyun.messagemgt.dto.vo.weixin.WeixinReturnModelVO;
import com.aliyun.messagemgt.util.redis.Redis;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IDEA
 * 此实现用redis作为缓存
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/1/25
 * @time:10:15
 */
@Component
public class TokenUtilImpl implements TokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(TokenUtilImpl.class);

    private static final String KEY = "com.pushcenter.";
    //@Value("${wechat.token.url}")
    private String tokenUrl;

    @Override
    public String getToken(PushChannelInfo pushChannelInfo) {
        String token = Redis.getValue(KEY + pushChannelInfo.getCorpSecret());
        logger.info(" redis中获取的token {} ",token);
        // 如果redis中获取不到则重新获取
        if (token == null) {
            logger.info("redis 中没有{} 的token信息，重新获取", pushChannelInfo);
            token = updateAndgetToken(pushChannelInfo);
        }
        return token;
    }

    @Override
    public String updateAndgetToken(PushChannelInfo pushChannelInfo) {
        // 取相应corpId和corpSecret参数
        Map<String, String> params = new HashMap<>(4);
        params.put(WeixinConstant.CORP_ID, pushChannelInfo.getCorpId());
        params.put(WeixinConstant.CORP_SECRET, pushChannelInfo.getCorpSecret());
        String token = null;
        try {
            HttpClientResult httpClientResult = HttpClientUtils.doGet(tokenUrl, params);
            // 将结果值类型转化
            WeixinReturnModelVO weixinReturnModelVO = JSON.parseObject(httpClientResult.getContent(), WeixinReturnModelVO.class);
            token = weixinReturnModelVO.getAccessToken();
            // token放到redis中
            logger.info("将{} 的token信息{}放到redis中", pushChannelInfo, weixinReturnModelVO);
            if(StringUtils.isNotBlank(token)){
                Redis.setXX(KEY + pushChannelInfo.getCorpSecret(), token, weixinReturnModelVO.getExpiresIn());
            }
        } catch (Exception e) {
            logger.error("get token erro", e);
        }
        return token;
    }

}
